package com.tourlaid.mamagerment.util;

import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.PutObjectResponse;
import com.tourlaid.mamagerment.common.Contant;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by xiaoyongge on 2017/9/22.
 * 百度云 bos 上传图片
 */
public class BosUtil {

    static String Access_Key_ID = "8ed74a9e287a4bee87ab978974b63c40";

    static String Secret_Access_Key = "9e920fac13d4481a828557767278248e";

    // 初始化一个BosClient
    private static class BosUtilHolder {
        private final static BosClient client = getBosClient();

        private static BosClient getBosClient() {
            BosClientConfiguration config = new BosClientConfiguration();
            config.setCredentials(new DefaultBceCredentials(Access_Key_ID, Secret_Access_Key));
            return new BosClient(config);
        }
    }

    public static BosClient getInstance() {
        return BosUtilHolder.client;
    }

    static class PrixAndData {

        String suffix;// 图片格式

        byte[] data;// 图片内容

        public PrixAndData(String suffix, byte[] bs) {
            this.suffix = suffix;
            this.data = bs;
        }
    }

    //校验
    private static PrixAndData validata(String base64Data) throws Exception {
        String dataPrix = "";// 图片格式
        String data = "";// 图片内容
        if (StringUtils.isEmpty(base64Data)) {
            throw new Exception("上传失败，上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败，数据不合法");
            }
        }

        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)
                || "data:image/jpg;".equalsIgnoreCase(dataPrix)) {// 编码的jpeg图片数据

            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {// 编码的icon图片数据

            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {// 编码的gif图片数据

            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {// 编码的png图片数据

            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }

        // 因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包

        byte[] bs = Base64Utils.decodeFromString(data);
        //限制文件大小为4m以内

        if (bs.length > 1024 * 1024) {
            throw new Exception("图片文件大小必须在1M以内！");
        }

        return new PrixAndData(suffix, bs);
    }


    public static List<String> PutObject(String bucketName, List<String> base64Data) throws Exception {
        List<PrixAndData> prixAndDataList = new ArrayList<PrixAndData>();
        for (int i = 0; i < base64Data.size(); i++) {
            prixAndDataList.add(validata(base64Data.get(i)));
        }
        List<String> pathList = new ArrayList<String>();

        for (int j = 0; j < prixAndDataList.size(); j++) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 新文件名格式：项目根路径+upload+日期+uuid+后缀名
            String newFileName = new StringBuffer(uuid).append(prixAndDataList.get(j).suffix).toString();
            BosClientConfiguration config = new BosClientConfiguration();
            config.setCredentials(new DefaultBceCredentials(Access_Key_ID, Secret_Access_Key));
            config.setEndpoint("http://" + Contant.BOS_HOST);
            BosClient client = new BosClient(config);
            // 以二进制串上传Object
            PutObjectResponse putObjectResponseFromByte = client.putObject(bucketName, newFileName, prixAndDataList.get(j).data);
            String path = "http://" + bucketName + "." + Contant.BOS_HOST + "/" + newFileName;
            pathList.add(path);
        }
        return pathList;
    }

    public static String PutObject(String bucketName, String base64Data) throws Exception {
        PrixAndData prixAndData = validata(base64Data);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 新文件名格式：项目根路径+upload+日期+uuid+后缀名
        String newFileName = new StringBuffer(uuid).append(prixAndData.suffix).toString();
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(Access_Key_ID, Secret_Access_Key));
        config.setEndpoint("http://" + Contant.BOS_HOST);
        BosClient client = new BosClient(config);
        // 以二进制串上传Object
        PutObjectResponse putObjectResponseFromByte = client.putObject(bucketName, newFileName, prixAndData.data);
        String path = "http://" + bucketName + "." + Contant.BOS_HOST + "/" + newFileName;
        return path;
    }
}
